// 默认引入当前目录的所有index.js文件
const ModulesFile = require.context('./', true, /index.js$/)

//接口列表
var apilist = {}

// keys 方法返回一个由文件名组成的数组, 如：['./app.js', './settings.js', './user.js']
ModulesFile.keys().map((key) => {
	if (key === "./index.js") return;

	const item = ModulesFile(key).default

	var mod = {}

	//替换路径
	var name = key.replace(/\.\/(.*)\/index.js/, '$1');

	mod[name] = item

	Object.assign(apilist, mod)
})

const install = (Vue, vm) => {
	//加载模块
	apilist;

	//循环组合接口API
	let api = {}

	for (let ModeName in apilist) {
		if (JSON.stringify(apilist[ModeName]) == '{}') {
			continue;
		}

		for (let ApiName in apilist[ModeName]) {
			let config = apilist[ModeName][ApiName]
			config.name = ApiName


			if (!config.name || !config.url) {
				continue;
			}

			if (!api[ModeName]) {
				api[ModeName] = {};
			}

			switch (config.method.toUpperCase()) {
				case 'GET':
					api[ModeName][config.name] = (data = {}) => {
						return uni.$u.http.get(config.url, {
							params: data
						});
					}
					break;
				case 'POST':
					api[ModeName][config.name] = (data = {}) => {
						return uni.$u.http.post(config.url, data);
					}
					break;
				case 'UPLOAD':
					api[ModeName][config.name] = (data = {}) => {
						if (data.filePath) {
							return uni.$u.http.upload(config.url, data);
						} else {
							return uni.$u.http.post(config.url, data);
						}
					}
					break;
			}
		}
	}

	vm.$u.api = api;
}

export default {
	install
};